<template>
  <view class="itemIist">
    <view class="item-list">
      <view class="item-list-item" v-for="item in teamList" :key="item.id">
        <view class="item-header">
          <view class="course-info">
            <text class="course-name">{{ item.courseName }}</text>
            <text class="team-name">班期：{{ item.teamName }}</text>
          </view>
          <view class="stats-badge">
            <text class="iconfont icon-renyuan"></text>
            <text>{{ item.studentTotal }}人</text>
          </view>
        </view>

        <view class="item-content">
          <view class="teacher-info">
            <text class="label">负责人</text>
            <text class="value">{{ item.teacherName }}</text>
          </view>

          <view class="exam-times">
            <view class="time-item" v-if="item.theoryTime">
              <text class="label">理论考试</text>
              <text class="value">{{ parseTime(item.theoryTime) }}</text>
            </view>
            <view class="time-item" v-if="item.theoryRetakeTime">
              <text class="label">理论补考</text>
              <text class="value">{{ parseTime(item.theoryRetakeTime) }}</text>
            </view>
            <view class="time-item" v-if="item.practicalTime">
              <text class="label">实操考试</text>
              <text class="value">{{ parseTime(item.practicalTime) }}</text>
            </view>
            <view class="time-item" v-if="item.practicalRetakeTime">
              <text class="label">实操补考</text>
              <text class="value">{{ parseTime(item.practicalRetakeTime) }}</text>
            </view>
          </view>
        </view>

        <view class="item-footer">
          <uv-button type="primary" @click="showDetail(item)" :customStyle="{
            width: '160rpx',
            height: '64rpx',
            borderRadius: '32rpx',
            fontSize: '26rpx'
          }">查看详情</uv-button>
        </view>
      </view>
    </view>

    <m-tabbar fixed fill :current="0" :tabbar="tabbar" :beforeChange="onBeforeChange">
      <template v-slot:tabbar_index_1>
        <view class="custom_style">
          <view class="iconfont icon-shouye1 custom_style_icon"></view>
        </view>
      </template>
    </m-tabbar>

    <uv-popup ref="detailPopup" mode="bottom" round="10" closeable :closeOnClickOverlay="false"
      :customStyle="{ height: '85vh', overflow: 'hidden', backgroundColor: '#F7F6F9' }">
      <view class="detail-popup">
        <view class="popup-header">
          <text class="title">培训安排</text>
        </view>
        <scroll-view scroll-y class="popup-content" :scroll-top="scrollTop" @scrolltolower="onLoadMore"
          refresher-enabled :refresher-triggered="isRefreshing" @refresherrefresh="onRefresh">
          <view class="info-cards">
            <view v-for="(chapter, index) in chapterList" :key="index" class="info-card">
              <view class="card-header">
                <view class="course-info">
                  <text class="course-name">{{ chapter.title }}</text>
                  <text class="chapter-count" v-if="chapter.chapterItems.length">
                    {{ chapter.chapterItems.length }}个培训项目
                  </text>
                </view>
              </view>

              <view class="card-content">
                <!-- 培训项目列表 -->
                <view class="section-title">
                  <text class="icon">|</text>
                  <text>培训项目</text>
                </view>
                <view class="project-list">
                  <view class="project-item" v-for="(item, idx) in chapter.chapterItems" :key="idx">
                    <text class="iconfont icon-project"></text>
                    <text class="item-name">{{ item.title }}</text>
                  </view>
                </view>

                <!-- 培训时间列表 -->
                <view class="section-title">
                  <text class="icon">|</text>
                  <text>培训安排</text>
                </view>
                <view class="schedule-list">
                  <view class="schedule-item" v-for="(date, dateIdx) in chapter.times" :key="dateIdx">
                    <view class="date-header">
                      <text class="date">{{ parseTime(date.startTime, '{y}-{m}-{d}') }}</text>
                      <text class="status-tag" :class="getDateStatusClass(date.startTime)">
                        {{ getDateStatusText(date.startTime) }}
                      </text>
                    </view>
                    <view class="time-slots">
                      <view class="time-slot">
                        <view class="time-info">
                          <text class="time">{{ parseTime(date.startTime, '{h}:{i}') }} - {{ parseTime(date.endTime,
                            '{h}:{i}') }}</text>
                          <text class="room">教室：{{ date.room }}</text>
                          <text class="status-text" :class="getTimeStatusClass(date.startTime, date.endTime)">
                            {{ getTimeStatusText(date.startTime, date.endTime) }}
                          </text>
                        </view>
                        <view class="teacher-info">
                          <text class="teacher-label">授课教师:</text>
                          <view class="teacher-list">
                            <view class="teacher-item" v-for="(teacher, tIdx) in date.teachers" :key="tIdx">
                              <image class="teacher-avatar" :src="teacher.avatar || 'https://img.qiananquang.com/minapp/avatar.png'"
                                mode="aspectFill"></image>
                              <text class="teacher-name">{{ teacher.name }}</text>
                            </view>
                          </view>
                        </view>
                      </view>
                    </view>
                  </view>
                </view>
              </view>

              <view class="card-footer">
                <view class="footer-left">
                  <text class="student-total">
                    <text class="iconfont icon-yonghu"></text>
                    培训学员：<text class="num">{{ detailData.studentTotal || 0 }}人</text>
                  </text>
                </view>
                <view class="footer-right">
                  <button class="btn-students" @click="navigateToStudents(chapter)">
                    <text class="iconfont icon-mingdan"></text>
                    学员名单
                  </button>
                </view>
              </view>
            </view>
          </view>
          <view class="loading-more" v-if="isLoading">
            <text>加载中...</text>
          </view>
        </scroll-view>
      </view>
    </uv-popup>
  </view>
</template>

<script>
import { parseTime } from '@/utils/tools.js'
import { getTeacherTeamList, getTeamDetail } from '@/http/teacher.js'
export default {

  components: {},
  data() {
    return {
      parseTime,
      teamList: [],
      exam: {},
      query: {
        pageNum: 1,
        pageSize: 10
      },
      tabbar: {
        color: "#7a7e83",
        selectedColor: "#fb4736",
        backgroundColor: "#f7f7f7",
        list: [{
          pagePath: "pages/teacher/itemList",
          text: "班级管理",
          iconPath: "/static/img/manage.png",
          selectedIconPath: "/static/img/manage-hover.png"
        }, {
          pagePath: "",
          text: "扫码",
          iconPath: "/static/img/saoma.png",
          selectedIconPath: "/static/img/saoma.png"
        },
        {
          pagePath: "pages/teacher/userinfo",
          text: "个人中心",
          iconPath: "/static/img/userinfo.png",
          selectedIconPath: "/static/img/userinfo-hover.png"
        }]
      },
      chapterList: [],
      detailData: {},
      scrollTop: 0,
      isLoading: false,
      isRefreshing: false,
      scanResult: null,
    }
  },
  computed: {},
  methods: {
    onBeforeChange(next, index) {
      console.log(next, index)
      if (index == 1) {
        // 调用扫码
        this.scanCode()
      } else {
        next()
      }
    },
    getTeamList() {
      uni.showLoading({
        title: '加载中',
        mask: true
      })
      getTeacherTeamList(this.query).then(res => {
        this.teamList = res.data.list
        uni.hideLoading()
      })
    },
    async showDetail(item) {
      this.itemId = item.id
      try {
        const res = await getTeamDetail({ teamId: item.id })
        this.detailData = res.data
        this.chapterList = res.data.course.chapters
        this.$refs.detailPopup.open()
        console.log(111);
        
      } catch (err) {
        uni.showToast({
          title: '获取详情失败',
          icon: 'none'
        })
      }
    },
    closeDetail() {
      this.$refs.detailPopup.close()
    },
    navigateToStudents(chapter) {
      console.log(chapter, 'chapter', this.itemId);
      // return
      uni.navigateTo({
        url: `/pages/teacher/studentList?teamId=${this.itemId}&chapterId=${chapter.id}&title=${chapter.title}`
      })
    },
    async onRefresh() {
      this.isRefreshing = true
      try {
        const res = await getTeamDetail({ teamId: this.itemId })
        this.detailData = res.data
        this.chapterList = res.data.course.chapters
      } catch (err) {
        uni.showToast({
          title: '刷新失败',
          icon: 'none'
        })
      } finally {
        this.isRefreshing = false
      }
    },
    onLoadMore() {
      // 如果需要加载更多数据，在这里实现
      console.log('加载更多')
    },
    // 获取日期状态样式类
    getDateStatusClass(date) {
      const today = new Date().getTime()
      const targetDate = new Date(date).setHours(23, 59, 59)
      if (targetDate < today) return 'status-ended'
      if (targetDate === today) return 'status-ongoing'
      return 'status-upcoming'
    },

    // 获取日期状态文本
    getDateStatusText(date) {
      const today = new Date().getTime()
      const targetDate = new Date(date).setHours(23, 59, 59)
      if (targetDate < today) return '已结束'
      if (targetDate === today) return '进行中'
      return '未开始'
    },

    // 获取时间段状态样式类
    getTimeStatusClass(startTime, endTime) {
      const now = new Date().getTime()
      const start = new Date(startTime).getTime()
      const end = new Date(endTime).getTime()

      if (end < now) return 'status-ended'
      if (start <= now && now <= end) return 'status-ongoing'
      return 'status-upcoming'
    },

    // 获取时间段状态文本
    getTimeStatusText(startTime, endTime) {
      const now = new Date().getTime()
      const start = new Date(startTime).getTime()
      const end = new Date(endTime).getTime()

      if (end < now) return '已结束'
      if (start <= now && now <= end) return '进行中'
      return '未开始'
    },
    // 扫码方法
    scanCode() {
      // 检查权限
      uni.authorize({
        scope: 'scope.camera',
        success: () => {
          // 调用扫码
          uni.scanCode({
            onlyFromCamera: true, // 只允许相机扫码
            scanType: ['qrCode'], // 只扫二维码
            success: (res) => {
              console.log('扫码成功:', res)
              this.handleScanResult(res.result)
            },
            fail: (err) => {
              console.error('扫码失败:', err)
              uni.showToast({
                title: '扫码失败',
                icon: 'none'
              })
            }
          })
        },
        fail: () => {
          // 用户拒绝授权
          uni.showModal({
            title: '提示',
            content: '需要相机权限才能扫码，是否去设置？',
            success: (res) => {
              if (res.confirm) {
                // 打开设置页面
                uni.openSetting()
              }
            }
          })
        }
      })
    },
    // 处理扫码结果
    handleScanResult(result) {
      try {
        console.log('扫码结果:', result)
        // 解析URL参数
        const parseUrlParams = (url) => {
          const paramsStr = url.split('?')[1] || ''
          const params = {}
          if (paramsStr) {
            paramsStr.split('&').forEach(item => {
              const [key, value] = item.split('=')
              params[key] = decodeURIComponent(value || '')
            })
          }
          return params
        }
        
        // 获取参数部分
        const queryString = result.split('#')[1] || result
        const params = parseUrlParams(queryString)
        
        // 转换参数类型
        const formattedParams = {
          studentId: params.studentId,
          courseId: params.courseId,
          chapterId: params.chapterId
        }
        
        // 验证必要参数
        if (!formattedParams.courseId) {
          throw new Error('无效的二维码类型')
        }

        console.log('解析后的参数:', params)
        uni.navigateTo({
          url: `/pages/time/checkUser?studentId=${params.studentId}&courseId=${params.courseId}${params.chapterId ? `&chapterId=${params.chapterId}` : ''}`
        })

      } catch (error) {
        console.error('处理扫码结果失败:', error)
        uni.showToast({
          title: error.message || '无效的二维码格式',
          icon: 'none'
        })
      }
    },
    // 处理签到逻辑
    async handleAttendance(params) {
      try {
        // 验证签到时间
        const now = Date.now()
        if (now < params.startTime || now > params.endTime) {
          throw new Error('不在签到时间范围内')
        }

        // 调用签到接口
        const res = await checkAttendance({
          id: params.id,
          studentId: params.studentId,
          startTime: params.startTime,
          endTime: params.endTime
        })

        uni.showToast({
          title: `${params.title}签到成功`,
          icon: 'success'
        })

        // 刷新列表
        this.getTeamList()
      } catch (error) {
        console.error('签到失败:', error)
        uni.showToast({
          title: error.message || '签到失败',
          icon: 'none'
        })
      }
    },
  },
  watch: {},

  // 页面周期函数--监听面加载
  onLoad() {
    this.getTeamList()
  },
  // 页面周期函数--监听页面初次渲染完成
  onReady() { },
  // 页面周期函数--监听页面显示(not-nvue)
  onShow() { },
  // 页面周期函数--监听页面隐藏
  onHide() { },
  // 页面周期函数--监听页面卸载
  onUnload() { },
  // 页面处理函数--监听用户下拉动作
  // onPullDownRefresh() { uni.stopPullDownRefresh(); },
  // 页面处理函数--监听用户上拉触底
  // onReachBottom() {},
  // 页面处理函数--监听页面滚动(not-nvue)
  // onPageScroll(event) {},
  // 页面处理函数--用户点击右上角分享
  // onShareAppMessage(options) {},
}
</script>

<style lang="scss" scoped>
.itemIist {
  background: #F5F6F8;
  min-height: 100vh;
  padding: 20rpx;
}

.item-list {
  &-item {
    background: #FFFFFF;
    border-radius: 16rpx;
    margin-bottom: 20rpx;
    overflow: hidden;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);

    .item-header {
      padding: 24rpx;
      background: #F8F9FC;
      display: flex;
      justify-content: space-between;
      align-items: flex-start;

      .course-info {
        flex: 1;
        margin-right: 20rpx;

        .course-name {
          font-size: 32rpx;
          font-weight: 600;
          color: #333;
          display: block;
          margin-bottom: 8rpx;
        }

        .team-name {
          font-size: 26rpx;
          color: #666;
        }
      }

      .stats-badge {
        background: #E8F7FF;
        padding: 8rpx 16rpx;
        border-radius: 24rpx;
        display: flex;
        align-items: center;
        gap: 4rpx;

        .iconfont {
          font-size: 24rpx;
          color: #0086FF;
        }

        text {
          font-size: 24rpx;
          color: #0086FF;
        }
      }
    }

    .item-content {
      padding: 24rpx;

      .teacher-info {
        display: flex;
        align-items: center;
        margin-bottom: 20rpx;

        .label {
          font-size: 26rpx;
          color: #666;
          margin-right: 20rpx;
        }

        .value {
          font-size: 26rpx;
          color: #333;
          font-weight: 500;
        }
      }

      .exam-times {
        background: #F8F9FC;
        padding: 20rpx;
        border-radius: 12rpx;

        .time-item {
          display: flex;
          justify-content: space-between;
          padding: 12rpx 0;

          &:not(:last-child) {
            border-bottom: 2rpx solid #EBEDF0;
          }

          .label {
            font-size: 26rpx;
            color: #666;
          }

          .value {
            font-size: 26rpx;
            color: #333;
          }
        }
      }
    }

    .item-footer {
      padding: 20rpx 24rpx;
      display: flex;
      justify-content: flex-end;
      border-top: 2rpx solid #F5F6F8;
    }
  }
}

.custom_style {
  color: #FD3523;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: 24rpx;

  &_icon {
    background-color: #FD3523;
    color: #fff;
    font-size: 80rpx;
    width: 120rpx;
    height: 120rpx;
    border-radius: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: -40rpx;
  }
}

.slot-content {
  padding: 30rpx;

  text {
    display: block;
    padding: 10rpx 0;
  }
}

.detail-popup {
  height: 100%;
  display: flex;
  flex-direction: column;

  .popup-header {
    padding: 30rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    border-bottom: 2rpx solid #F0F0F0;
    background: #fff;

    .title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }

  .popup-content {
    flex: 1;
    height: calc(85vh - 94rpx);
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;
  }

  .info-cards {
    padding: 30rpx;

    .info-card {
      background: #FFFFFF;
      border-radius: 20rpx;
      padding: 30rpx;
      margin-bottom: 30rpx;
      box-shadow: 0 2rpx 20rpx rgba(0, 0, 0, 0.03);

      .card-header {
        margin-bottom: 20rpx;

        .course-info {
          display: flex;
          align-items: center;

          .course-name {
            font-size: 32rpx;
            font-weight: bold;
            color: #333;
            margin-right: 20rpx;
          }

          .chapter-count {
            font-size: 24rpx;
            color: #FD3523;
            padding: 4rpx 12rpx;
            background: rgba(253, 53, 35, 0.1);
            border-radius: 6rpx;
          }
        }
      }

      .section-title {
        display: flex;
        align-items: center;
        margin: 30rpx 0 20rpx;

        .icon {
          color: #FD3523;
          font-size: 32rpx;
          font-weight: bold;
          margin-right: 10rpx;
        }

        text {
          font-size: 30rpx;
          font-weight: bold;
          color: #333;
        }
      }

      .project-list {
        display: flex;
        flex-wrap: wrap;
        gap: 16rpx;

        .project-item {
          background: #F8F8F8;
          padding: 16rpx 24rpx;
          border-radius: 8rpx;
          display: flex;
          align-items: center;

          .iconfont {
            font-size: 28rpx;
            color: #FD3523;
            margin-right: 8rpx;
          }

          .item-name {
            font-size: 26rpx;
            color: #333;
          }
        }
      }

      .schedule-list {
        .schedule-item {
          margin-bottom: 30rpx;

          .date-header {
            margin-bottom: 16rpx;

            .date {
              font-size: 28rpx;
              color: #333;
              font-weight: bold;
            }
          }

          .time-slots {
            .time-slot {
              background: #F8F8F8;
              border-radius: 12rpx;
              padding: 20rpx;
              margin-bottom: 16rpx;
              transition: all 0.3s;

              .time-info {
                display: flex;
                justify-content: space-between;
                margin-bottom: 12rpx;

                .time {
                  font-size: 26rpx;
                  color: #333;
                }

                .room {
                  font-size: 26rpx;
                  color: #666;
                }
              }

              .teacher-info {
                display: flex;
                align-items: center;

                .teacher-label {
                  font-size: 26rpx;
                  color: #666;
                  margin-right: 16rpx;
                }

                .teacher-list {
                  display: flex;
                  gap: 20rpx;
                  flex-wrap: wrap;

                  .teacher-item {
                    display: flex;
                    align-items: center;
                    background: #fff;
                    padding: 8rpx 16rpx;
                    border-radius: 30rpx;

                    .teacher-avatar {
                      width: 40rpx;
                      height: 40rpx;
                      border-radius: 50%;
                      margin-right: 8rpx;
                    }

                    .teacher-name {
                      font-size: 26rpx;
                      color: #333;
                    }
                  }
                }
              }

              &:hover {
                transform: translateY(-2rpx);
                box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
              }
            }
          }
        }
      }

      .card-footer {
        margin-top: 30rpx;
        padding-top: 20rpx;
        border-top: 2rpx solid #F5F5F5;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .footer-left {
          .student-total {
            font-size: 26rpx;
            color: #666;
            display: flex;
            align-items: center;

            .iconfont {
              font-size: 28rpx;
              margin-right: 8rpx;
              color: #FD3523;
            }

            .num {
              color: #FD3523;
              font-weight: bold;
            }
          }
        }

        .footer-right {
          display: flex;
          gap: 16rpx;

          .btn-students {
            background: #FFF0EF;
            color: #FD3523;
            padding: 0 24rpx;
            height: 64rpx;
            border-radius: 32rpx;
            font-size: 26rpx;
            border: none;
            display: flex;
            align-items: center;
            justify-content: center;

            .iconfont {
              margin-right: 8rpx;
              font-size: 28rpx;
              color: #FD3523;
            }
          }
        }
      }
    }
  }
}

.loading-more {
  text-align: center;
  padding: 20rpx 0;
  color: #999;
  font-size: 24rpx;
}

.schedule-list {
  .schedule-item {
    .date-header {
      .status-tag {
        font-size: 24rpx;
        padding: 4rpx 12rpx;
        border-radius: 20rpx;

        &.status-ended {
          background: #F5F5F5;
          color: #999;
        }

        &.status-ongoing {
          background: #E6F7FF;
          color: #1890FF;
        }

        &.status-upcoming {
          background: #F6FFED;
          color: #52C41A;
        }
      }
    }

    .time-slots {
      .time-slot {
        .time-info {
          .status-text {
            // position: absolute;
            // right: 0;
            // top: 50%;
            // transform: translateY(-50%);
            font-size: 24rpx;
            padding: 4rpx 12rpx;
            border-radius: 20rpx;

            &.status-ended {
              background: #F5F5F5;
              color: #999;
            }

            &.status-ongoing {
              background: #E6F7FF;
              color: #1890FF;
            }

            &.status-upcoming {
              background: #F6FFED;
              color: #52C41A;
            }
          }
        }
      }
    }
  }
}
</style>